package com.jbm.le;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.jbm.onehome.iface.IEGuardKey;
import com.jbm.onehome.iface.IEGuardKeyCtrl;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * Created by Sun on 2016/11/23.
 */

public class OpenCtrl
{
	private final static String TAG = OpenCtrl.class.getSimpleName();
	private BTDoorCtrl m_btdoorctrl;
	private JBMBLEEGuard m_jbmbleeguard;
	private int m_trytimes;
	private int m_timeout;
	private long m_SCAN_PERIOD;
	private HashMap<String,Integer> m_macmap;
	private DoorEvent m_doorevent;
	private Context m_context;
	private IEGuardKeyCtrl m_keyctrl;
	private Handler mScanner;
	private Handler mHandler;
	private BluetoothAdapter mBluetoothAdapter = null;
	private String m_resname = UUID.randomUUID().toString();
	private boolean m_scan_open;

	private final ServiceConnection mBTDCConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName componentName, IBinder service) {
			m_btdoorctrl = ((BTDoorCtrl.LocalBinder) service).getService();
			if (!m_btdoorctrl.initialize()) {
				Log.e(TAG, "Unable to initialize Bluetooth");
				if ( m_doorevent != null )
					m_doorevent.OtherError("初始化蓝牙失败");
				return;
			}
			// Automatically connects to the device upon successful start-up initialization.

			if ( SysLog.g_syslog == null )
				SysLog.g_syslog = new SysLog("jbmc.log", 31,31);

			scanLeDevice(true);
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			m_btdoorctrl = null;
		}
	};

	private final ServiceConnection mJBMBLEEGConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName componentName, IBinder service) {
			m_jbmbleeguard = ((JBMBLEEGuard.LocalBinder) service).getService();
			if (!m_jbmbleeguard.initialize()) {
				Log.e(TAG, "Unable to initialize Bluetooth");
				return;
			}
			// Automatically connects to the device upon successful start-up initialization.

			scanLeDevice(true);
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName)
		{
			m_jbmbleeguard = null;
		}
	};

	public void Open (int timeout, int trytimes, IEGuardKeyCtrl avkey, final Context context, Activity act, DoorEvent doorevent, boolean scan_open )
	{
		m_macmap = new HashMap<String, Integer>();

		m_doorevent = doorevent;
		m_context = context;
		m_keyctrl = avkey;
		for(int i=0;i<m_keyctrl.EGKlist.length;i++){
			Log.e("main",m_keyctrl.IndexofList(i).mac);
		}
		m_SCAN_PERIOD = (timeout+666)*(trytimes+1)+4333;
		m_trytimes = trytimes;
		m_timeout = timeout;
		m_scan_open = scan_open;
		mHandler = new Handler();
		mScanner = new Handler();

		// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
		if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
			Toast.makeText(context,"本手机不支持BLE", Toast.LENGTH_SHORT).show();
			if ( doorevent != null )
				doorevent.OtherError("本手机不支持BLE");
			return;
		}

		// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
		final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();

		// 检查设备上是否支持蓝牙
		if (mBluetoothAdapter == null) {
			Toast.makeText(context, "本手机不支持蓝牙", Toast.LENGTH_SHORT).show();
			if ( doorevent != null )
				doorevent.OtherError("本手机不支持蓝牙");
			return;
		}

		boolean first = false;

		if (act!=null)
			if (!mBluetoothAdapter.isEnabled())
			{
				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

				act.startActivityForResult(enableBtIntent, 1);
			}

		long ct = System.currentTimeMillis();

		while ( !mBluetoothAdapter.isEnabled() )
		{
			if ( System.currentTimeMillis() - ct > m_SCAN_PERIOD )
				break;

			try
			{
				Thread.sleep(5);
			}catch (Exception ee){}
		}

		// Initializes list view adapter.

		if ( mBluetoothAdapter.isEnabled() )
		{
			Log.d(TAG, "bindService ...... service");

/*
			final Intent gattServiceIntent = new Intent(context, JBMBLEEGuard.class);
			boolean r = context.bindService(gattServiceIntent, mJBMBLEEGConnection, BIND_AUTO_CREATE);
*/
			final Intent gattServiceIntent = new Intent(context, BTDoorCtrl.class);
			boolean r = context.bindService(gattServiceIntent, mBTDCConnection, BIND_AUTO_CREATE);
		}else if ( doorevent != null )
			doorevent.OtherError("蓝牙未打开");
		return;
	}

	private void scanLeDevice(final boolean enable)
	{
		if (enable)
		{
			try
			{
				if ( m_btdoorctrl != null )
				{
					if (m_btdoorctrl.m_once.poll(0, TimeUnit.MILLISECONDS) == null)
					{
						if (m_doorevent != null)
							m_doorevent.OtherError("稍等，上一次操作还未完成");
						return;
					}
				}else if ( m_doorevent != null )
						m_doorevent.OtherError("BTDoorCtrl is null");
			}catch ( Exception e)
			{
				if ( m_doorevent != null )
					m_doorevent.OtherError("稍等，上一次操作还未完成");
				return;
			}

			if ( mBluetoothAdapter.isEnabled() )
			{
				// Stops scanning after a pre-defined scan period.
				mHandler.postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						mBluetoothAdapter.stopLeScan(mLeScanCallback);
						if (m_macmap.size() == 0)
							if (m_doorevent != null)
								m_doorevent.NotFound();

						if ( m_btdoorctrl != null )
							m_btdoorctrl.m_once.offer(1);
					}
				}, m_SCAN_PERIOD);

				mBluetoothAdapter.startLeScan(mLeScanCallback);
			}else if ( m_btdoorctrl != null )
				m_btdoorctrl.m_once.offer(1);
		} else
		{
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback()
	{

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)
		{
			for ( int i = 0; i < m_keyctrl.EGKlist.length; i ++ )
				if ( m_keyctrl.EGKlist[i].mac.equals(device.getAddress()))
				{
					synchronized (this)
					{
						Integer o = m_macmap.get(m_keyctrl.EGKlist[i].mac);

						if ( o != null )
							return;
						else
							m_macmap.put(m_keyctrl.EGKlist[i].mac,1);
					}

					final IEGuardKey ekey = m_keyctrl.EGKlist[i];

					if ( m_btdoorctrl != null )
					{
						if (!m_scan_open)
							mBluetoothAdapter.stopLeScan(mLeScanCallback);
						if ( m_doorevent != null )
							m_doorevent.OpenStatus("找到蓝牙门禁，连接中...");
						m_btdoorctrl.connect(ekey, m_doorevent, m_resname, m_trytimes, m_timeout);
/*
						Handler handler = new Handler(Looper.getMainLooper());
						handler.post(new Runnable()
						{
							@Override
							public void run()
							{
								m_btdoorctrl.connect(ekey, m_doorevent, m_resname, m_trytimes, m_timeout);
							}
						});
*/
					}

					if ( m_jbmbleeguard != null )
					{
						mBluetoothAdapter.stopLeScan(mLeScanCallback);
						Handler handler = new Handler(Looper.getMainLooper());
						handler.post(new Runnable()
						{
							@Override
							public void run()
							{
								m_jbmbleeguard.connect(ekey, m_doorevent, m_resname);
							}
						});
					}
				}
		}
	};
}
